//
//  This copyrighted © code is written for and is part of the book
//  Smartphone-Based Real-Time Digital Signal Processing
//
package com.dsp.spectrogram;

import java.util.concurrent.BlockingQueue;

public class Processing implements Runnable{
	
	private BlockingQueue<WaveFrame> input;
	private BlockingQueue<WaveFrame> output;
	private Thread filterThread;
	private Spectrogram filter;
	private int counter1, counter2;
	
	public Processing(BlockingQueue<WaveFrame> input, BlockingQueue<WaveFrame> output) {
		this.input = input;
		this.output = output;
		counter1 = counter2 = 0;
		filter = new Spectrogram();
        filterThread = new Thread(this);
        filterThread.start();
	}

	public void run() {
		try {
			loop:while(true) {
				WaveFrame currentFrame = null;
				currentFrame = input.take();
				if(currentFrame == Settings.STOP){
					Settings.getCallbackInterface().notify("Average Frame Processing Time: " + filter.getTime() + "ms");
					filter.release();
					output.put(currentFrame);
					break loop;
				}
				filter.process(currentFrame.getAudio());
				currentFrame.setDebug(filter.getDebug(Settings.debugOutput));
				if(Settings.graphReady.get()) {
					if(counter2++ == Settings.secondConstant/30){
						Settings.getDataListener().notifyDataArray(filter.getDebug(-5));
						counter2 = 0;
					}
				}
				if(counter1++ == Settings.secondConstant){
					Settings.getCallbackInterface().notify("Frame Processing Time: " + filter.getTime() + "ms");
					counter1 = 0;
				}
				output.put(currentFrame);
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			e.printStackTrace();
		}
	}
}